const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');

function getMultiplier(level) {
    if (level >= 1 && level <= 40) return 150;
    if (level >= 41 && level <= 70) return 200;
    if (level >= 71 && level <= 160) return 300;
    return 150;
}

function parseDoc(doc) {
    const map = new Map();
    const lines = doc.split(/\r?\n/);
    for (const line of lines) {
        if (!/^\d+\s*,/.test(line)) continue;
        const parts = line.split(',').map(s => s.trim());
        if (parts.length < 3) continue;
        const level = parseInt(parts[0], 10);
        const tenHour = Number(parts[2]);
        if (!Number.isNaN(level) && !Number.isNaN(tenHour)) {
            map.set(level, tenHour);
        }
    }
    return map;
}

async function main() {
    const projectRoot = path.resolve(__dirname, '..');
    const docPath = path.join(projectRoot, 'doc', '训练经验.md');
    const doc = fs.readFileSync(docPath, 'utf8');
    const docMap = parseDoc(doc);

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };

    const samples = [15, 22, 30, 40, 41, 50, 60, 70, 90, 120];
    let conn;
    try {
        conn = await mysql.createConnection(db);
        const results = [];
        for (const lvl of samples) {
            const [rows] = await conn.execute('SELECT standard_exp_per_fight FROM level_experience WHERE level = ?', [lvl]);
            const dbValue = rows && rows[0] ? Number(rows[0].standard_exp_per_fight || 0) : 0;
            const tenHour = docMap.get(lvl) || 0;
            const m = getMultiplier(lvl);
            const expected = tenHour ? Math.floor(tenHour / (m * 10 * 1.1)) : 0;
            results.push({ level: lvl, dbValue, expected, ok: dbValue === expected });
        }

        const okCount = results.filter(r => r.ok).length;
        console.log(`对比完成：${okCount}/${results.length} 相符`);
        for (const r of results) {
            console.log(`等级 ${r.level}: DB=${r.dbValue}, 期望=${r.expected}, ${r.ok ? '✅' : '❌'}`);
        }
    } catch (e) {
        console.error('校验失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
